<template>
  <div class="page-content">
    <div class="header">
      <h3>教练管理</h3>
    </div>
    <!-- 表格菜单 -->
    <el-tabs v-model="tableLayout" class="demo-tabs" @tab-change="handleClick" style="margin-top: 20px">
      <el-tab-pane label="驾校管理" name="1"> </el-tab-pane>
      <el-tab-pane label="车型分类" name="2"> </el-tab-pane>
      <el-tab-pane label="报名地点" name="3"> </el-tab-pane>
      <el-tab-pane label="招生员" name="4"> </el-tab-pane>
      <el-tab-pane label="教练管理" name="5"> </el-tab-pane>
      <el-tab-pane label="训练场" name="6"> </el-tab-pane>
    </el-tabs>
    <!-- 表格菜单 -->
    <el-row style="margin-top: 20px;">
      <div style="width: 12px"></div>
      <el-col :xs="24" :sm="12" :lg="6" class="el-col2">
        <el-button @click="showDialog('add')" v-ripple>新增教练</el-button>
      </el-col>
    </el-row>

    <art-table :data="tableData" :loading="tableLoading" :currentPage="pageNum" :pageSize="pageSize" :total="pageTotal"
      @current-change="currentChange" @size-change="sizeChange">
      <template #default>
        <el-table-column label="ID" prop="id" width="55" align="center" />
        <el-table-column label="排序" prop="sortOrder" align="center" />
        <el-table-column label="教练姓名" width="400">
          <template #default="scope">
            <div class="title_box">
              <div class="title_box_left" v-if="scope.row.avatar">
                <img class="tableimg" :src="scope.row.avatar" />
              </div>
              <div class="title_box_right">
                <div class="bankcont_title">
                  <div class="bankcont_title_text">{{ scope.row.name }}</div>
                </div>
                <div style="clear: both"></div>
                <div class="cartcont">
                  <el-button v-for="usertag in scope.row.usertag" :key="usertag" round size="small">
                    {{ usertag }}
                  </el-button>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="联系电话" prop="phone" align="center" />
        <el-table-column #default="scope" label="状态" align="center">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
            @click="editStatus(scope.row.id, scope.row)" />
        </el-table-column>
        <el-table-column label="创建时间：" prop="createTime" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150px" align="center">
          <template #default="scope">
            <button-table type="edit" @click="buttonMoreClick(scope.row)" />
            <button-table type="delete" @click="deleteRole(scope.row.id)" />
          </template>
        </el-table-column>
      </template>
    </art-table>

    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增教练' : '编辑教练'" width="30%"
      :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="排序" prop="sortOrder">
          <el-input v-model="form.sortOrder" :rows="3" />
        </el-form-item>
        <el-form-item label="教练姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-input v-model="form.avatar" style="display: none"></el-input>
          <div class="avatar-uploader" @click="showImageChooseDialog = true">
            <el-image v-if="form.avatar" :src="form.avatar" class="avatar" fit="contain"></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
                <Plus />
              </el-icon></i>
            <div v-if="form.avatar" class="mask">替换</div>
            <el-icon v-if="form.avatar" class="del-image" :size="20" @click.stop="handleDelImg">
              <CircleCloseFilled />
            </el-icon>
          </div>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <!-- 单选 -->
          <el-radio-group v-model="form.gender">
            <el-radio :value="0">男</el-radio>
            <el-radio :value="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="教龄" prop="drivingYears">
          <el-input v-model="form.drivingYears">
            <template #append> 年 </template>
          </el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="form.age">
            <template #append> 年 </template>
          </el-input>
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-checkbox-group v-model="selectedValues">
            <el-checkbox v-for="option in options" :key="option.value" :value="option.value" size="large">
              {{ option.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="简介" prop="introduction">
          <el-input type="textarea" :rows="6" v-model="form.introduction" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit(formRef)">提交</el-button>
        </div>
      </template>
    </el-dialog>
    <image-selected-dialog v-if="showImageChooseDialog" :single-type="selectImageSingle"
      :show-image-choose-dialog="showImageChooseDialog" @close-dialog="handleCloseImageDialog"
      :operationType="false"></image-selected-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { getCoach, AddCoachInfo, EditCoachInfo, DelCoachInfo } from '@/api/driverSchoolApi'
import ImageSelectedDialog from '@/views/decoration/diyComponents/ImageSelectedDialog.vue'

const dialogVisible = ref(false)
const tableLayout = ref('5')
const options = ref([
  { value: '01', label: '热情' },
  { value: '02', label: '面善' },
  { value: '03', label: '优质' }
])
const selectedValues = ref(['01'])

const formRef = ref<FormInstance>()
const router = useRouter() // 使用useRouter获取路由实例

const rules = reactive<FormRules>({
  typename: [
    { required: true, message: '请输入报名名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  sortOrder: [{ required: true, message: '请输入正确排序', trigger: 'blur' }],
  avatar: [{ required: true, message: '请上传头像', trigger: 'change' }]
})

const form = reactive({
  id: Number(''),
  sortOrder: 1,
  avatar: '',
  name: '',
  phone: '',
  gender: '',
  drivingYears: '',
  age: '',
  introduction: '',
  tags: '',
  status: 1
})

const showImageChooseDialog = ref(false)
const selectImageSingle = ref(true)
const handleCloseImageDialog = (value: any) => {
  if (value && value.fileUrl) {
    form.avatar = value.fileUrl
  }
  showImageChooseDialog.value = false
}

const tableData = ref([])

const dialogType = ref('add')
const currentChange = (val: number) => {
  pageNum.value = val
  getData()
}

const sizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  getData()
}

const showDialog = (type: string, row?: any) => {
  dialogVisible.value = true
  dialogType.value = type

  if (type === 'edit' && row) {
    form.id = row.id
  } else {
    form.id = Number('')
    form.avatar = ''
    form.name = ''
    form.phone = ''
    form.gender = '0'
    form.drivingYears = ''
    form.age = ''
    form.introduction = ''
    selectedValues.value = ['01']
    form.status = 1
    headerPic.value = ''
  }
}

const buttonMoreClick = (row: any) => {
  showDialog('edit', row)
  Object.assign(form, {
    avatar: row.avatar,
    sortOrder: row.sortOrder,
    name: row.name,
    phone: row.phone,
    gender: row.gender,
    drivingYears: row.drivingYears,
    age: row.age,
    introduction: row.introduction,
    tags: row.tags,
    headerPic: row.avatar,
    status: row.status
  })
  headerPic.value = row.avatar
  selectedValues.value = row.tags.split(',')
}

const deleteRole = (id: number) => {
  ElMessageBox.confirm('确定删除该教练吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(async () => {
    const res = await DelCoachInfo(id)
    if (res.code === '00000') {
      ElMessage.success('删除成功')
      getData()
    }
  })
}

const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (valid) {
      const isAdd = dialogType.value === 'add'
      const message = dialogType.value === 'add' ? '新增成功' : '修改成功'
      const params = {
        storeId: parseInt(localStorage.getItem('lty-store-id') || '0'),
        sortOrder: form.sortOrder,
        avatar: form.avatar,
        name: form.name,
        phone: form.phone,
        gender: form.gender,
        drivingYears: form.drivingYears,
        age: form.age,
        introduction: form.introduction,
        tags: selectedValues.value.join(','),
        status: form.status
      }
      let res
      if (isAdd) {
        res = await AddCoachInfo(params)
      } else {
        res = await EditCoachInfo(form.id, { ...params, id: form.id })
      }
      if (res.code === '00000') {
        ElMessage.success(message)
        dialogVisible.value = false
        getData()
      }
    }
  })
}

interface studentParams {
  status: number
  id: number
  sortOrder: number
  avatar: string
  name: string
  phone: string
  gender: number
  drivingYears: string
  age: string
  introduction: string
  tags: string
}
async function editStatus(id: any, params: studentParams) {
  try {
    const res = await EditCoachInfo(id, {
      status: params.status,
      id: params.id,
      storeId: parseInt(localStorage.getItem('lty-store-id') || '0'),
      sortOrder: params.sortOrder,
      avatar: params.avatar,
      name: params.name,
      phone: params.phone,
      gender: params.gender,
      drivingYears: params.drivingYears,
      age: params.age,
      introduction: params.introduction,
      tags: selectedValues.value.join(',')
    })
    if (res.code === '00000') {
      ElMessage.success('修改成功')
    }
  } catch (e) {
  } finally {
    await getData()
  }
}

const formatDate = (date: string) => {
  return new Date(date)
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
    .replace(/\//g, '-')
}
const tableLoading = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
async function getData() {
  try {
    tableLoading.value = true

    const { code, data } = await getCoach({
      pageNum: pageNum.value,
      pageSize: pageSize.value
    })
    if (code === '00000') {
      tableData.value = data.list
      pageTotal.value = data.total
    }
  } catch (e) {
  } finally {
    tableLoading.value = false
  }
}
const headerPic = ref('')

const handleClick = (e: any) => {
  if (e === '1') {
    setTimeout(() => {
      router.push('/drivingschool/DrivingschoolManagement')
    }, 0)
  } else if (e === '2') {
    setTimeout(() => {
      router.push('/drivingschool/question_bank_type')
    }, 0)
  } else if (e === '3') {
    setTimeout(() => {
      router.push('/drivingschool/question_bank_type_baoming')
    }, 0)
  } else if (e === '4') {
    setTimeout(() => {
      router.push('/drivingschool/question_bank_type_zhaosheng')
    }, 0)
  } else if (e === '5') {
    setTimeout(() => {
      router.push('/drivingschool/question_bank_type_jiaolian')
    }, 0)
  } else if (e === '6') {
    setTimeout(() => {
      router.push('/drivingschool/question_bank_type_xunlianchang')
    }, 0)
  }
}
const handleDelImg = () => {
  form.avatar = ''
}

onMounted(() => {
  getData()
})
</script>

<style lang="scss" scoped>
.page-content {
  .svg-icon {
    width: 1.8em;
    height: 1.8em;
    overflow: hidden;
    vertical-align: -8px;
    fill: currentcolor;
  }
}

.title_box_left {
  float: left;
  width: 4.5rem;
  height: 4.5rem;
  border-radius: 0.5rem;
  overflow: hidden;
  margin-right: 1rem;

  .tableimg {
    width: 100%;
    height: 100%;
  }
}

.title_box_right {
  float: right;
  float: left;
}

.bankcont_title_text {
  height: 2rem;
  margin-top: 0.3rem;
}

.columnvideo {
  border-radius: 0.5rem;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;

  .mask {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 24px;
    background-color: rgba(0, 0, 0, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
    color: #fff;
    font-size: 12px;
  }

  .del-image {
    display: none;
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
    color: #8c939d;
  }

  &:hover .mask {
    opacity: 1;
  }

  &:hover .del-image {
    display: block;
  }
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
